package org.bot.client.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNullApi;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 沧月
 * @create 0014 2023/9/14 19:06
 * @description <description class purpose>
 */

@Component
public class Bean implements ApplicationContextAware {

    private static ApplicationContext context;

    static Logger logger = LoggerFactory.getLogger(ApplicationContextAware.class);


    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static Events getEvents(String name) {
        return (Events) context.getBean(name);
    }


    public static JSONArray getEventList() {
        final Map<String, Events> beansOfType = context.getBeansOfType(Events.class);
        JSONArray array = new JSONArray();
        beansOfType.forEach((k, v) -> {
            String name = v.getClass()
                    .getAnnotation(EventName.class).value();
            logger.info(String.format("加载功能::  %s", name));
            array.fluentAdd(
                    new JSONObject()
                            .fluentPut("event", k)
                            .fluentPut("eventName", name)
            );
        });
        return array;
    }
}
